package org.my.tcp;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;

import java.nio.charset.StandardCharsets;

/**
 * 处理器
 */
public class NettyServerHandler extends ChannelInboundHandlerAdapter {

    /**
     * 读取消息
     *
     * @param ctx
     * @param msg
     * @throws Exception
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        System.out.println("ctx=" + ctx);
        //将msg转成byteBuf
        // 这个是Netty的 ByteBuf 不是 NIO的ByteBuffer
        ByteBuf byteBuf = (ByteBuf) msg;
        System.out.println("客户端发送的消息是:" + byteBuf.toString(StandardCharsets.UTF_8));
        System.out.println("客户端地址:" + ctx.channel().remoteAddress());

    }

    /**
     * 读取完毕回复
     *
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.writeAndFlush(Unpooled.copiedBuffer("hello client!", StandardCharsets.UTF_8));
    }

    /**
     * 读写超时处理
     * @param ctx
     * @param evt
     * @throws Exception
     */
    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if(evt instanceof IdleStateEvent){ //超时事件
            IdleStateEvent idleEvent= (IdleStateEvent) evt;
            if(idleEvent.state()== IdleState.READER_IDLE){
                System.out.println("读超时");
                ctx.channel().close();
            }

        }
    }
}
